package com.zshan.clinic.cms.config;

import com.zshan.clinic.common.enums.YesOrNoEnum;
import com.zshan.clinic.common.util.string.StringUtil;
import lombok.Data;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.SentinelServersConfig;
import org.redisson.config.SingleServerConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import java.util.List;

/**
 * redission 配置
 */
@Configuration
@EnableConfigurationProperties(com.zshan.clinic.cms.config.RedissonConfig.RedissonProperties.class)
public class RedissonConfig {

    @Autowired
    private Environment environment;

    @Data
    @ConfigurationProperties(prefix = "spring.redis")
    public static class RedissonProperties {
        private String password;
        private Integer database;

        //集群配置
        private Sentinel sentinel;

        //单例配置
        private String host;
        private String port;
        @Data
        public static class Sentinel {
            private String master;
            private List<String> nodes;
        }
    }

    @Autowired
    private RedissonProperties redissonProperties;

    @Bean(destroyMethod = "shutdown")
    public RedissonClient redissonClient() {
        String isSentinel = YesOrNoEnum.NO.getValue();
        //如果是测试环境或者生产环境用的是集群其他的用的单例
        Config config = new Config();
        if(YesOrNoEnum.YES.getValue().equals(isSentinel)){
            //哨兵集群模式
            SentinelServersConfig sentinelConfig = config.useSentinelServers()
                    .setMasterName(redissonProperties.getSentinel().getMaster());
            // 把节点字符串拆开，添加到sentinel节点列表

            for (String node : redissonProperties.getSentinel().getNodes()) {
                sentinelConfig.addSentinelAddress("redis://" + node.trim());
            }
            sentinelConfig.setDatabase(redissonProperties.getDatabase());
            if (StringUtil.isNotBlank(redissonProperties.getPassword())) {
                sentinelConfig.setPassword(redissonProperties.getPassword());
            }
        }else{
            //
            SingleServerConfig singleConfig = config.useSingleServer()
                    .setAddress("redis://" + redissonProperties.getHost()+":"+redissonProperties.getPort());
            singleConfig.setDatabase(redissonProperties.getDatabase());
            if (StringUtil.isNotBlank(redissonProperties.getPassword())) {
                singleConfig.setPassword(redissonProperties.getPassword());
            }
        }
        return Redisson.create(config);
    }
}

